package com.gupao.javavip.java;

import org.junit.Test;

import java.util.concurrent.TimeUnit;

public class VolatileExample {
    private static boolean flag = false;
    private Thread thread = new Thread(() -> {
        try {
            TimeUnit.MILLISECONDS.sleep(100);
            flag = true;
            System.out.println("flag 被修改成 true");
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

    /**
     * 死循环
     * 可添加 -Djava.compiler=NONE jvm参数，关闭JIT及时编译
     */
    @Test
    public void test1() {
        int i = 0;
        thread.start();
        while (!flag) {
            i++;
        }
        System.out.println("程序结束,i=" + i);
    }

    @Test
    public void test2() {
        int i = 0;
        thread.start();
        while (!flag) {
            i++;
            System.out.println("flag:" + flag);
        }
        System.out.println("程序结束,i=" + i);
    }

    @Test
    public void test3() throws InterruptedException {
        int i = 0;
        thread.start();
        while (!flag) {
            i++;
            TimeUnit.MILLISECONDS.sleep(100);
        }
        System.out.println("程序结束,i=" + i);
    }

    @Test
    public void test4() throws InterruptedException {
        Integer i = 0;
        thread.start();
        while (!flag) {
            i++;
        }
        System.out.println("程序结束,i=" + i);
    }

    @Test
    public void test5() {
        int i = 0;
        new Thread(() -> {
            try {
//                TimeUnit.MILLISECONDS.sleep(100);
                flag = true;
//                System.out.println("flag 被修改成 true");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        while (!flag) {
            i++;
        }
        System.out.println("程序结束,i=" + i);
    }
}
